#!/usr/bin/env bash
set -euo pipefail

buildType="${1:-}"
packageName="${2:-$buildType}"

if [[ -z "${buildType}" ]]; then
	echo "用法: $0 <buildType(DEBUG|RELEASE)> [packageName]" >&2
	exit 1
fi

projectPath="C:/mateurp_pipline/mateurp/mateurp"
curr_buildIdFile="$projectPath/Build/build_id_${buildType}.txt"
if [[ ! -f "$curr_buildIdFile" ]]; then
	echo "未找到构建号文件: $curr_buildIdFile" >&2
	exit 1
fi
curr_buildId="$(tr -d '\r\n' < "$curr_buildIdFile")"

aarFileNameOrgin="mate_android_${packageName}.aar"
aarFileName="mate_android_${packageName}_${curr_buildId}.aar"

# 获取本机 IPv4
ip="$(ipconfig 2>/dev/null | sed -n 's/.*IPv4[^:]*: *\([0-9.]*\).*/\1/p' | head -n1 || true)"
if [[ -z "${ip}" ]]; then
	ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
fi
if [[ -z "${ip}" ]]; then
	ip="127.0.0.1"
fi
downloadUrl="http://${ip}/"

destDir="C:/mateurp_pipline/Mate"
mkdir -p "$destDir"

if [[ "${buildType}" == "DEBUG" ]]; then
	srcPath="${projectPath}/Build/Android/DEBUG/MateAi/unityLibrary/build/outputs/aar/unityLibrary-debug.aar"
	mv -f "$srcPath" "${destDir}/${aarFileName}"
fi

if [[ "${buildType}" == "RELEASE" ]]; then
	srcPath="${projectPath}/Build/Android/RELEASE/MateAi/unityLibrary/build/outputs/aar/unityLibrary-release.aar"
	mv -f "$srcPath" "${destDir}/${aarFileName}"
fi

echo "downloadUrl: ${downloadUrl}${aarFileName}"
cp -f "${destDir}/${aarFileName}" "${destDir}/${aarFileNameOrgin}"

buildDir="C:/mateurp_pipline/mateurp/mateurp/Build/Android/${buildType}/MateAi/unityLibrary"
symbolFileName="mate_android_symbols_${packageName}_${curr_buildId}.zip"

# 生成 symbols.zip
symbolsZip="${buildDir}/symbols.zip"
rm -f "$symbolsZip"
if command -v 7z >/dev/null 2>&1; then
	7z a -r "$symbolsZip" "${buildDir}/symbols/*" >/dev/null
elif [[ -x "/c/Program Files/7-Zip/7z.exe" ]]; then
	"/c/Program Files/7-Zip/7z.exe" a -r "$symbolsZip" "${buildDir}/symbols/*" >/dev/null
elif [[ -x "C:/Program Files/7-Zip/7z.exe" ]]; then
	"C:/Program Files/7-Zip/7z.exe" a -r "$symbolsZip" "${buildDir}/symbols/*" >/dev/null
else
	(
		cd "$buildDir"
		zip -r "symbols.zip" "symbols" >/dev/null
	)
fi

mv -f "$symbolsZip" "${destDir}/${symbolFileName}"
symbleUrl="http://${ip}/${symbolFileName}"
echo "symbleUrl: ${symbleUrl}"

json=$(printf '{"text":{"content":"本地安卓AAR打包完成,下载地址 %s%s or %s%s  符号地址 %s"},"msgtype":"text"}' "$downloadUrl" "$aarFileName" "$downloadUrl" "$aarFileNameOrgin" "$symbleUrl")
echo "$json"

curl --ssl-no-revoke -H "Content-Type: application/json" -X POST -d "$json" "https://oapi.dingtalk.com/robot/send?access_token=1dd9ef311951334ba9e001f194f78c99ee8b74fff2c56b5f899c1727302f60b8" || true

exit 0